
/*
 * Copyright (c) 2020 Actions Semiconductor Co., Ltd
 *
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @file
 * @brief micin detect driver for Actions SoC
 */

#include <errno.h>
#include <kernel.h>
#include <string.h>
#include <init.h>
#include <adc.h>
#include <hotplug.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <board.h>
#include <gpio.h>

#define SYS_LOG_DOMAIN "MICIN_DETECT"
#define SYS_LOG_LEVEL CONFIG_SYS_LOG_MICIN_DETECT_LEVEL
#include <logging/sys_log.h>

struct micin_detect_info {

	struct device *dectect_gpio_dev;
};

struct micin_detect_config {
	char *adc_name;
	u16_t adc_chan;
};


static int micin_detect_state(struct device *dev, int *state)
{
	struct micin_detect_info *micin_detect = dev->driver_data;
	int err, value;
	err = gpio_pin_read(micin_detect->dectect_gpio_dev, BOARD_MICIN_DETECT_GPIO,
			    &value);
	if (err) {
		return 0;
	}

	if (value == BOARD_MICIN_DETECT_GPIO_VALUE) {
		*state = MICIN_IN;
	} else {
		*state = MICIN_OUT;
	}
	return 0;
}

static const struct hotplog_detect_driver_api micin_detect_driver_api = {
	.detect_state = micin_detect_state,
};

static int micin_detect_init(struct device *dev)
{
	struct micin_detect_info *micin_detect = dev->driver_data;
	printk("line in detect init!!!\n");
	micin_detect->dectect_gpio_dev = device_get_binding(BOARD_MICIN_DETECT_GPIO_NAME);
	if (!micin_detect->dectect_gpio_dev) {
		SYS_LOG_ERR("device binding failed %s\n", BOARD_MICIN_DETECT_GPIO_NAME);
		return -ENODEV;
	}
	printk("GPIO init!!!\n");
	gpio_pin_configure(micin_detect->dectect_gpio_dev, BOARD_MICIN_DETECT_GPIO, GPIO_DIR_IN | GPIO_PUD_PULL_UP);
	return 0;
}

static struct micin_detect_info micin_detect_ddata;



DEVICE_AND_API_INIT(micin_detect, "micin_detect",
		    micin_detect_init,
		    &micin_detect_ddata, NULL,
		    POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE,
		    &micin_detect_driver_api);
